<!DOCTYPE html>
<link rel="help" href="https://github.com/samuelgoto/idle-detection">
<title>Tests the Idle Detection API</title>
<script src="/resources/test-only-api.js"></script>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/idle-detection/resources/idle-detection-helper.js"></script>
<script>
'use strict';

// setMainWindowHidden is duplicated from resources/visibility.js.
// This is necessary to have the test in wpt_internal.
function setMainWindowHidden(hidden) {
  return new Promise((resolve, reject) => {
    if (!window.testRunner) {
      reject("no window.testRunner present");
      return;
    }
    if (document.visibilityState == (hidden ? "hidden" : "visible")) {
      reject("setMainWindowHidden(" + hidden + ") called but already " + hidden);
      return;
    }
    document.addEventListener("visibilitychange", resolve, {once:true});
    testRunner.setMainWindowHidden(hidden);
  });
}

promise_setup(async t => {
  await internals.setPermission({name: 'notifications'}, 'granted',
                                location.origin, location.origin);
  if (isChromiumBased) {
    await loadChromiumResources();
  }
})

promise_test(async t => {
  let monitor;

  expect(addMonitor).andReturn(async (monitorPtr) => {
      monitor = monitorPtr;
      return {
        error: IdleDetectorError.SUCCESS,
        state: {
          idleTime: null,
          screenLocked: false
        }
      };
    });

  const controller = new AbortController();
  const detector = new IdleDetector();
  const watcher = new EventWatcher(t, detector, ["change"]);
  const initial_state = watcher.wait_for("change");

  await detector.start({threshold: 60000, signal: controller.signal});
  await initial_state;

  assert_equals(detector.userState, "active");

  setMainWindowHidden(true);

  monitor.update(
          {
            idleTime: { milliseconds: 0 },
            screenLocked: false
          },
          /*is_overridden_by_devtools=*/true
        );

  // Assert that the detector works while the page is not visible.
  await watcher.wait_for("change");
  assert_equals(detector.userState, "idle");

  setMainWindowHidden(false);

  monitor.update(
          {
            idleTime: null,
            screenLocked: false
          },
          /*is_overridden_by_devtools=*/true
        );

  await watcher.wait_for("change");
  assert_equals(detector.userState, "active");

  controller.abort();
}, 'Page visibility.');

</script>
